import { Checkbox } from 'antd';
import { CheckboxChangeEvent } from 'antd/lib/checkbox';
import { useDispatch, useSelector } from 'dva';
import React from 'react';
import { GaugeSurvey } from './../../api';
import { IGauge } from './../../assets/js/DataJson';
import { AuthCompount } from './../../components';
import { IGlobal } from './../../Model/GlobalModel';
import { ISurvey } from './../../Model/SurveyModel';
import SurveyModelUtil from './../../utils/Survey/SurveyModelUtil';
import './ModuleTitle.scss';
interface IProps {
  data: IGauge;
  children?: React.ReactNode;
  pId: string;
}
// tslint:disable-next-line:no-any
declare var window: any;
/**
 * 小模块标题组件
 */
const isPc = window.screen.width > 500;

function ModuleTitle(props: IProps) {
  const answer = useSelector(({ survey }: { survey: ISurvey }) => survey.answer);
  const gaugeData = useSelector(({ survey }: { survey: ISurvey }) => survey.gaugeData);
  const writeType = useSelector(({ survey }: { survey: ISurvey }) => survey.writeType);
  const visitNumber = useSelector(({ survey }: { survey: ISurvey }) => survey.visitNumber);
  const patientId = useSelector(({ survey }: { survey: ISurvey }) => survey.patientId);
  const roleType = useSelector(({ survey }: { survey: ISurvey }) => survey.roleType);
  const initVisitNumber = useSelector(({ global }: { global: IGlobal }) => global.sysConfig.initVisitNumber);
  const dispatch = useDispatch();
  const surveyModelUtil = new SurveyModelUtil();
  answer.beforeModuleNames = answer.beforeModuleNames || [];
  // 显示上次内容
  const checkboxChange = async (e: CheckboxChangeEvent) => {
    const { result } = await GaugeSurvey.answerLastInfo({ visitNumber: visitNumber - 1, patientId });
    // tslint:disable-next-line:no-any
    const answerJson: any = JSON.parse(result.answerJson);
    gaugeData.forEach(item => {
      item.moduleChildrens.forEach(sub => {
        if (sub.moduleName === props.data.moduleName) {
          sub.subjects.forEach(sje => {
            const isVal = answerJson[sje.subjectData.field] || typeof answerJson[sje.subjectData.field] === 'number';
            if (e.target.checked) {
              answer[sje.subjectData.field] = answerJson[sje.subjectData.field];

              /**
               * 显示上次方式内容
               * 直接跳过props传值
               * 通过onlastSurvey 通知具体的组件更新
               */
              if (window[`onlastSurvey_${sje.subjectData.field}`]) {
                window[`onlastSurvey_${sje.subjectData.field}`](
                  answerJson[sje.subjectData.field],
                  sje.subjectData.field
                );
              }

              // 这里暂时没有做复合组件的判断 这里单纯处理输入框的输入😈
              if (document.getElementById(sje.subjectData.field)) {
                // tslint:disable-next-line:no-any
                (document.getElementById(sje.subjectData.field) as any).value = answerJson[sje.subjectData.field] || '';
              }
              sje.subjectData.errMsg = '';
              if (!isVal || JSON.stringify(answerJson[sje.subjectData.field]) === '[]') {
                // 如果上次方式没有对应的答案则显示 未找到上次内容
                sje.subjectData.errMsg = '未找到上次内容';
              }
            } else {
              answer[sje.subjectData.field] = null;
              sje.subjectData.errMsg = '';
              sje.subjectData.defaultValue = null;
              if (window[`onlastSurvey_${sje.subjectData.field}`]) {
                window[`onlastSurvey_${sje.subjectData.field}`](null);
              }
              // window.onlastSurvey(null, sje.subjectData.field);
              if (document.getElementById(sje.subjectData.field)) {
                // tslint:disable-next-line:no-any
                (document.getElementById(sje.subjectData.field) as any).value = null;
              }
            }
          });
        }
      });
    });
    if (e.target.checked) {
      answer.beforeModuleNames.push(props.data.moduleName);
    } else {
      answer.beforeModuleNames = answer.beforeModuleNames.filter((item: string) => item !== props.data.moduleName);
    }
    const payload = { writeType, visitNumber };
    const surveyInitData = await surveyModelUtil.surveyInit(gaugeData, answer, roleType, payload);
    const data = await surveyModelUtil.visibleIfChange(
      surveyInitData.gaugeData,
      surveyInitData.countData,
      surveyInitData.answer,
      surveyInitData.schema
    );
    dispatch({
      type: 'survey/directSave',
      payload: { ...data, isCache: true, restLoad: true },
    });
  };
  const explain = props.data.explain ? <div dangerouslySetInnerHTML={{ __html: props.data.explain }} /> : <div />;
  return (
    <div id={props.pId}>
      <div id="ModuleTitle">
        <div className="sm_tit sp">
          <div className="sm_tit">
            <div className="bor" />
            <div className="tit_bor">
              <div>{props.data.moduleName}</div>
              <AuthCompount
                // tslint:disable-next-line:jsx-no-multiline-js
                isShow={
                  Number(visitNumber) !== 1 &&
                  Number(visitNumber) !== Number(initVisitNumber) &&
                  !!props.data.isReadLastSurvey &&
                  isPc
                }
              >
                <Checkbox
                  checked={answer.beforeModuleNames && answer.beforeModuleNames.includes(props.data.moduleName)}
                  // tslint:disable-next-line:jsx-no-multiline-js
                  defaultChecked={answer.beforeModuleNames && answer.beforeModuleNames.includes(props.data.moduleName)}
                  onChange={checkboxChange}
                >
                  读取上次访视内容
                </Checkbox>
              </AuthCompount>
            </div>
          </div>
          <AuthCompount isShow={false}>
            <div className="mus">* 代表必填项</div>
          </AuthCompount>
          <AuthCompount
            // tslint:disable-next-line:jsx-no-multiline-js
            isShow={
              Number(visitNumber) !== 1 &&
              !isPc &&
              Number(visitNumber) !== Number(initVisitNumber) &&
              !!props.data.isReadLastSurvey
            }
          >
            <Checkbox
              checked={answer.beforeModuleNames && answer.beforeModuleNames.includes(props.data.moduleName)}
              // tslint:disable-next-line:jsx-no-multiline-js
              defaultChecked={answer.beforeModuleNames && answer.beforeModuleNames.includes(props.data.moduleName)}
              onChange={checkboxChange}
              className="check_margin"
            >
              读取上次访视内容
            </Checkbox>
          </AuthCompount>
        </div>

        <AuthCompount isShow={!!props.data.explain}>
          <div className="exp">
            <span /> {explain}
          </div>
        </AuthCompount>
        {props.children}
      </div>
    </div>
  );
}
export default ModuleTitle;
